<?php
namespace app\common\logic;
use think\facade\Db;

/**
 * 订单
 */
class OrderLogic
{
    /**
     * 添加商品订单
     */
    public function add($goods,$post)
    {
        $user_id = $post['user_id'];
        // 仿制灌水 1天只能下 50 单
        $order_count = Db::name('Order')->where("user_id= ".$post['user_id']." and order_sn like '".date('Ymd')."%'")->count(); // 查找购物车商品总数量
        if($order_count >= 50){
            return array('status'=>0,'msg'=>'一天只能下50个订单');
        }
        $address_id = $post['address_id'];
        if($address_id){
            $address = Db::name('user_address')->where("address_id", $address_id)->find();
        } else {
            $address = Db::name('user_address')->where(['user_id'=>$post['user_id']])->order(['is_default'=>'desc'])->find();
        }
        if(!$address){
            return array('status'=>0,'msg'=>'请选择收货地址');
        }
        //多供货商
        $modtime = getCurTime();
        //统计价格字段
        $pricefilter = logic('GoodsLogic')->getFilterAttr(0);
        //获取运费
        $region_id = $address['city'];
        $special_region = Db::name('region')->where('(name like "%天津%") or (name like "%北京%") or (name like "%上海%") or (name like "%重庆%")')->column('id');
        if(in_array($address['province'],$special_region)){
            $region_id = $address['district'];
        }


        $ids = '';
        foreach($goods as $suid=>$sval){
            $freight_id = 0;
            if(!empty($post['freight_ids'])){
                $freight_ids = $post['freight_ids'];
                $freight_id = $freight_ids[$suid];
            }else{
                $freightList =logic('FreightLogic')->getList([['status','=',1],['sid','=',$suid]]);
                $cartList[$suid]['freightList'] = $freightList;
                $cartList[$suid]['freightkey'] = 0;
                $freight_id = $freightList[0]['template_id'];
            }
            $res_freight = logic('GoodsLogic')->getFreight( $goods,$address,$freight_id);
            if(!$res_freight['status']){
                return ['status'=>0,'msg'=>$res_freight['msg']??'获取运费失败'];
            }
            $freight = $res_freight['data'];
             $data = array(
                'order_sn'         =>$this->get_order_sn(), // 订单编号
                'user_id'          =>$post['user_id'], // 用户id
                'username'         =>$post['username'],
                'goods_id'         =>$sval['goods'][0]['goods_id'],
                'sid'        =>$suid?:0,//多供货商
                 's_user_id'        =>$suid?:0,//多供货商
                'consignee'        =>$address['consignee'], // 收货人
                'province'         =>$address['province']?$address['province']:0,//'省份id',
                'city'             =>$address['city']?$address['city']:0,//'城市id',
                'district'         =>$address['district']?$address['district']:0,//'县',
                'town'             =>$address['town']?$address['town']:0,// '街道',
                'address'          =>$address['address']?$address['address']:'',//'详细地址',
                'mobile'           =>$address['mobile']?$address['mobile']:'',//'手机',
                'zipcode'          =>$address['zipcode']?$address['zipcode']:'',//'邮编',
                'email'            =>$address['email']?$address['email']:'',//'邮箱',
                 'longitude'            =>$address['longitude']??'',//'经纬度',
                 'latitude'            =>$address['latitude']??'',//'经纬度',
                'add_time'         =>$modtime, // 下单时间
                'user_note'        =>$post['user_note'],//用户留言
                 'is_seckill'        =>$post['is_seckill'],//是否是秒杀产品
            );
            foreach($sval['goods'] as $gval){
                $gid = $gval['goods_id'];
                foreach($pricefilter as $fv){
                        if(empty($data['total_'.$fv])){
                            $data['total_'.$fv] = 0;
                        }
                     $data['total_'.$fv]+= $gval[$fv]*$gval['goods_num'];

                }
                $data['goods_nper'] = $gval['goods_nper']??'';
                //品牌积分使用优惠券抵扣
                if($gval['leixing_id']==1){
                    $data['total_youhui'] = bcmul($gval['youhui'],$gval['goods_num'],2);
                }else{
                    $data['total_youhui'] = 0;
                }
            }

            if(!isset($data['leixing_id'])){
                $data['leixing_id'] = Db::name('goods')->where('goods_id',$gid)->value('leixing_id');
            }
            if($data['leixing_id']==1){
                //报单区
                $level = Db::name('users')->where('user_id',$post['user_id'])->value('level');
                $user_level = Db::name('user_level')->where('rank',$level)->find();
                $user_up_money = $user_level['up_money']?:0;
                $now_up_money = bcadd($data['total_shop_price'],$user_up_money,2);
                $new_level = Db::name('user_level')->where(['up_money'=>$now_up_money,'rank'=>['gt',$level]])->find();
                if(!$new_level){
//                    return array('status'=>0,'msg'=>'下单金额未达升级条件');
                }
            }
            $data['shipping_price'] = isset($freight[$suid])?$freight[$suid]:0;
            $data['df_username'] = $post['df_username']??'';
            $data['coupon_money'] = $sval['coupon_money'];
            $coupon_ids = $sval['coupon_ids'];
            $data['coupon_ids'] = implode('',$coupon_ids);
            $data['use_score'] = $post['use_score'];
            if($post['use_score']){
                $data['pay_score'] = $sval['pay_score'];
                $data['score_money'] = $sval['score_money'];
            }else{
                $data['pay_score'] = 0;
                $data['score_money'] = 0;
            }
            $data['cuxiao_money'] = $sval['cuxiao_money'];


            $order_id = Db::name('order')->insertGetId($data);
            if($order_id === false){
                return array('status'=>0,'msg'=>'添加订单失败');
            }

            $ids.=','.$order_id;

            //订单分表
            $dataAll=[];
            foreach($sval['goods'] as $gval){
                //下单就减库存
                $rs = logic('Stock')->update_stock_log($post['user_id'], -$gval['goods_num'], array('goods_id' => $gval['goods_id'], 'goods_name' => $gval['goods_name'], 'spec_key_name' => $gval['spec_key_name'], 'spec_goods_id' => $gval['spec_goods_id']),$order_id);
                if(!$rs['status']){
                    return array('status'=>0,'msg'=>$rs['msg']);
                }

                $data2=[];
                $data2['sid'] = $suid?:0;
                $data2['user_id'] = $post['user_id'];
                $data2['order_id'] = $order_id;
                $data2['goods_id'] = $gval['goods_id'];
                $data2['goods_name'] = $gval['goods_name'];
                $data2['real_num'] = $gval['goods_num'];
                $data2['taozhuang_ids'] = $gval['taozhuang_ids'];
                $data2['goods_num'] = $gval['goods_num'];
//                $data2['spec_goods_id'] = $gval['spec_goods_id'];
                $data2['spec_key_name'] = $gval['spec_key_name'];
                foreach($pricefilter as $fv){
                    $data2[$fv]= $gval[$fv];
                }
                $data2['market_price'] = $gval['market_price'];
                $data2['goods_sn'] = $gval['goods_sn'];
                $data2['leixing_id'] = $data['leixing_id'];
                $data2['is_taozhuang'] = 0;
                $data2['is_seckill'] = $gval['is_seckill'];
                $dataAll[] = $data2;
            }
           // dump($pricefilter);
            $rs = Db::name('order_goods')->insertAll($dataAll);
            //dump($rs);exit;
            if($rs === false){
                return array('status'=>0,'msg'=>'添加订单分表失败');
            }
            //更新优惠券使用状态
            if($coupon_ids){
                Db::name('coupon_record')->where('user_id',$user_id)->where('id','in',$coupon_ids)->update(['status'=>1,'usetime'=>time()]);
            }
        }
        return array('status'=>1,'msg'=>'','result'=>trim($ids,','));
    }



    /**
     * 获取订单 order_sn
     * @return string
     */
    public function get_order_sn()
    {
        $order_sn = null;
        // 保证不会有重复订单号存在
        while(true){
            $order_sn = date('YmdHis').rand(100000,999999); // 订单编号
            $order_sn_count = Db::name('order')->where("order_sn = ".$order_sn)->count();
            if($order_sn_count == 0)
                break;
        }

        return $order_sn;
    }

    /**
     * 获取订单状态
     */
    public function getStatus(){
        return config('extra_status.order');
    }
    public function getRefundStatus(){
        return config('extra_status.order_refund');
    }
    public function getPeisongStatus(){
        return config('extra_status.peisong');
    }

    /**
	 * 取消订单
	 * @param $user_id|用户ID
	 * @param $order_id|订单ID
	 */
	public function cancel_order($user_id,$order_id){
		$order = Db::name('order')->where(array('order_id'=>$order_id,'user_id'=>$user_id))->find();
		//检查是否未支付订单
		if(empty($order))
			return array('status'=>-1,'msg'=>'订单不存在','result'=>'');
		if($order['order_status'] != 0){
			return array('status'=>-1,'msg'=>'订单状态错误','result'=>'');
		}

		$row = Db::name('order')->delete($order_id);
        if(!$row){
            return array('status'=>-1,'msg'=>'删除订单失败','result'=>'');
        }

        //先回退库存

        $goods = Db::name('order_goods')->whereIn('order_id',$order_id)->select();
        foreach($goods as $gval){
            $rs = logic('Stock')->update_stock_log($user_id, $gval['goods_num'], array('goods_id' => $gval['goods_id'], 'goods_name' => $gval['goods_name'], 'spec_key_name' => $gval['spec_key_name'], 'spec_goods_id' => $gval['spec_goods_id']),$order_id.'撤销');
            if(!$rs['status']){
                return array('status'=>0,'msg'=>$rs['msg']);
            }
        }
        //查询是否有已支付的抵扣
        if($order['total_fluse_pay']>0){
            $rs = qianbao($user_id,$order['total_fluse_pay'],'fuli','删除订单退款','支付单号'.$order_id);
            if(!$rs['status']){
                return $rs;
            }
        }
        if($order['total_quan_pay']>0){
            $rs = qianbao($user_id,$order['total_quan_pay'],'baodan2','删除订单退款','支付单号'.$order_id);
            if(!$rs['status']){
                return $rs;
            }
        }
        if($order['total_xfscore_pay']>0){
            $rs = qianbao($user_id,$order['total_xfscore_pay'],'baodan1','删除订单退款','支付单号'.$order_id);
            if(!$rs['status']){
                return $rs;
            }
        }

        if($order['total_youhui_pay']>0){
            $rs = qianbao($user_id,$order['total_youhui_pay'],'youhui','删除订单退款','支付单号'.$order_id);
            if(!$rs['status']){
                return $rs;
            }
        }

        $row = Db::name('order_goods')->whereIn('order_id',$order_id)->delete();
        if(!$row){
            return array('status'=>-1,'msg'=>'删除订单产品失败','result'=>'');
        }
        if($order['coupon_ids']){
            Db::name('coupon_record')->where('user_id',$user_id)->where('id','in',$order['coupon_ids'])->update(['status'=>0,'usetime'=>0]);
        }
		return array('status'=>1,'msg'=>'操作成功','result'=>'');
	}

    /**
     * 订单确认收货
     * @param $id 订单id
     * @param int $user_id
     * @return array
     */
    function confirm_order($id,$user_id = 0){
        $where['order_id'] = $id;
        if($user_id){
            $where['user_id'] = $user_id;
        }
        $order = Db::name('order')->where($where)->find();

        if($order['order_status'] != 2){
            return array('status'=>-1,'msg'=>'该订单状态有误');
        }

        $data = [];
        $data['order_status'] = 3; // 已收货
        $data['confirm_time'] = time(); // 收货确认时间

        $row = Db::name('order')->where(array('order_id'=>$id))->save($data);
        if(!$row)
            return array('status'=>-3,'msg'=>'更新订单状态失败');

        //更新分订单
        $row = Db::name('order_goods')->where(array('order_id'=>$id))->save($data);
        if(!$row){
            return array('status'=>-3,'msg'=>'更新产品订单状态失败');
        }
        //发放商家货款
        if($order['sid']>0){
            $supplier = Db::name('suppliers')->where('id',$order['sid'])->find();
            $price = $order['total_cost_price'];
            if($price>0){
                $res = qianbao_supply($order['sid'],$price,'s_money','商家货款发放','订单号'.$order['order_sn'],0,104);
                if(!$res['status']){
                    return $res;
                }
            }
        }
        return array('status'=>1,'msg'=>'操作成功');
    }

    /**
     * 添加评论
     * @param $add
     * @return array
     */
    public function add_comment($add){
        if(!$add['order_id'] || !$add['goods_id'])
            return array('status'=>-1,'msg'=>'非法操作','result'=>'');

        //检查订单是否已完成
        $order = Db::name('order')->field('order_status')->where("order_id", $add['order_id'])->where('user_id', $add['user_id'])->find();
        if($order['order_status'] != 3)
            return array('status'=>-1,'msg'=>'该笔订单还未确认收货','result'=>'');

        //检查是否已评论过
        $goods = Db::name('comment')->where(['order_id'=>$add['order_id'],'rec_id'=>$add['rec_id']])->find();
        if($goods)return array('status'=>-1,'msg'=>'您已经评论过该商品','result'=>'');
        if($add['goods_rank']<1 || $add['supply_rank']<1){
            return array('status'=>-1,'msg'=>'请给商品评分','result'=>'');
        }
        $row = Db::name('comment')->insert($add);
        if($row)
        {
            //更新订单商品表状态
            Db::name('order_goods')->where(array('rec_id'=>$add['rec_id'],'order_id'=>$add['order_id']))->update(array('is_comment'=>1,'order_status'=>4));
            Db::name('goods')->where(array('goods_id'=>$add['goods_id']))->setInc('comment_count',1); // 评论数加一
            // 查看这个订单是否全部已经评论,如果全部评论了 修改整个订单评论状态
            $comment_count   = Db::name('order_goods')->where("order_id", $add['order_id'])->where('is_comment', 0)->count();
            if($comment_count == 0) // 如果所有的商品都已经评价了 订单状态改成已评价
            {
                Db::name('order')->where("order_id",$add['order_id'])->update(array('order_status'=>4));
            }
            return array('status'=>1,'msg'=>'评论成功','result'=>'');
        }
        return array('status'=>-1,'msg'=>'评论失败','result'=>'');
    }

    /**
     * 添加店铺评论
     * @param $add
     * @return array
     */
    public function add_comment_supply($add){
        if(!$add['order_id'] || !$add['goods_id'])
            return array('status'=>-1,'msg'=>'非法操作','result'=>'');

        //检查订单是否已完成
        $order = Db::name('order')->field('order_status')->where("order_id", $add['order_id'])->where('user_id', $add['user_id'])->find();
        if($order['order_status'] != 3)
            return array('status'=>-1,'msg'=>'该笔订单还未确认收货','result'=>'');

        //检查是否已评论过
        $goods = Db::name('comment_supply')->where(['order_id'=>$add['order_id']])->find();
        if($goods)return array('status'=>-1,'msg'=>'您已经评论过该商家','result'=>'');
        if($add['supply_rank']<1){
            return array('status'=>-1,'msg'=>'请给商家评分','result'=>'');
        }
        $row = Db::name('comment_supply')->insert($add);
        if($row)
        {
            //更新订单商品表状态
            Db::name('order_goods')->where(array('rec_id'=>$add['rec_id'],'order_id'=>$add['order_id']))->update(array('is_supply_comment'=>1));
            Db::name('suppliers')->where(array('id'=>$add['sid']))->setInc('comment_count',1); // 评论数加一
            //更新商家平均评分
            $avg_score = Db::name('comment_supply')->where('sid',$add['sid'])->avg('supply_rank');
            Db::name('suppliers')->where(array('id'=>$add['sid']))->update(['comment_score'=>$avg_score]);
            return array('status'=>1,'msg'=>'评论成功','result'=>'');
        }
        return array('status'=>-1,'msg'=>'评论失败','result'=>'');
    }


    //寄卖
    public function jimai($id){
        $order = Db::name('order')->where(['order_id' => $id,'order_status'=>1])->find();
        if(!$order){
            return ['msg'=>'订单状态错误'];
        }

        if($order['leixing_id']!=1){
            return ['msg'=>'非套餐订单'];
        }

        $modtime = time();
        $save = [];
        $save['order_status'] = 4;//直接完成
        $save['jmtime'] = $modtime;
        $rs = Db::name('order')->where(['order_id'=>$id])->update($save);
        if($rs) {
            //更新分订单
            $rs = Db::name('order_goods')->where(['order_id' => $id])->update(['order_status' => 4]);
            if (!$rs) {
                return ['status'=>0,'msg'=>'更新产品订单状态失败'];
            }

            //更新会员寄卖状态
            $rs = Db::name('users')->where(['user_id'=>$order['user_id']])->update(['is_jm'=>1]);
            if($rs===false){
                return ['status'=>0,'msg'=>'更新会员寄卖状态失败'];
            }

            //给等额的参团积分
            if($order['total_shop_price']>=0.01){
                $rs = qianbao($order['user_id'],$order['total_shop_price'],'baodan1','套餐寄卖','单号'.$order['order_sn']);
                if(!$rs['status']){
                    return ['status'=>0,'msg'=>$rs['msg']];
                }
            }

        }else{
            return ['status'=>0,'msg'=>'更新订单状态失败'];
        }

        return ['status'=>1];
    }

    /**
     * 取消订单
     * @param $user_id|用户ID
     * @param $order_id|订单ID
     */
    public function cancel_userorder($order){
        //检查是否未支付订单
        $order_id = $order['order_id'];
        $user_id = $order['user_id'];
        if(empty($order))
            return array('status'=>-1,'msg'=>'订单不存在','result'=>'');
        if($order['order_status'] != 0){
            //return array('status'=>-1,'msg'=>'订单状态错误','result'=>'');
        }
        $row = Db::name('order')->delete($order_id);
        if(!$row){
            return array('status'=>-1,'msg'=>'删除订单失败','result'=>'');
        }
        //先回退库存
        $goods = Db::name('order_goods')->whereIn('order_id',$order_id)->select();
        foreach($goods as $gval){
            $rs = logic('Stock')->update_stock_log($user_id, -$gval['goods_num'], array('goods_id' => $gval['goods_id'], 'goods_name' => $gval['goods_name'], 'spec_key_name' => $gval['spec_key_name'], 'spec_goods_id' => $gval['spec_goods_id']),$order_id.'撤销');
            if(!$rs['status']){
                return array('status'=>0,'msg'=>$rs['msg']);
            }
        }
        //查询是否有已支付的抵扣
        if($order['df_username'] && $order['payment']){
            $df_userid = Db::name('users')->where(['username'=>$order['df_username']])->value('user_id');
            $pay_info = unserialize($order['payment']);
            foreach ($pay_info as $k=>$v){
                if($v<=0){
                    continue;
                }
                $rs = qianbao($df_userid,$v,$k,'删除订单退款','支付单号'.$order_id);
                if(!$rs['status']){
                    return $rs;
                }
            }
        }

        $row = Db::name('order_goods')->whereIn('order_id',$order_id)->delete();
        if(!$row){
            return array('status'=>-1,'msg'=>'删除订单产品失败','result'=>'');
        }
        return array('status'=>1,'msg'=>'操作成功','result'=>'');
    }

    public function getLogistics($shipping_code='',$delivery_no=''){
        if(empty($shipping_code) || empty($delivery_no)){
            return [];
        }
        $express_switch = tpCache('basic.express_switch');
        if($express_switch == 1){
            require_once(PLUGIN_PATH . 'kdniao/kdniao.php');
            $kdniao = new \kdniao();
            $data['OrderCode'] = date('YmdHis');
            $data['ShipperCode'] = $shipping_code;
            $data['LogisticCode'] = $delivery_no;
            $res = $kdniao->getOrderTracesByJson(json_encode($data));
            $res =  json_decode($res, true);
            if($res['State'] == 3){
                foreach ($res['Traces'] as $val){
                    $tmp['context'] = $val['AcceptStation'];
                    $tmp['time'] = $val['AcceptTime'];
                    $res['data'][] = $tmp;
                }
                $res['status'] = "200";
            }else{
                $res['message'] = $res['Reason'];
                $res['status'] = "0";
            }
            return $res;
        }else{
//            $url = "https://m.kuaidi100.com/query?type=".$shipping_code."&postid=".$delivery_no."&id=1&valicode=&temp=0.49738534969422676";
//            $resp = httpRequest($url,"GET");
//            return json_decode($resp,true);

            //====================================
            // 实时查询示例代码
            // 授权信息可通过链接查看：https://api.kuaidi100.com/manager/v2/myinfo/enterprise
            //====================================
            //参数设置
            $key = tpCache('basic.kuaidi100_key');// 客户授权key
            $customer = tpCache('basic.kuaidi100_customer');
            $param = array (
                'com' => $shipping_code,             // 快递公司编码
                'num' => $delivery_no,     // 快递单号
            );
            //请求参数
            $post_data = array();
            $post_data['customer'] = $customer;
            $post_data['param'] = json_encode($param, JSON_UNESCAPED_UNICODE);
            $sign = md5($post_data['param'].$key.$post_data['customer']);
            $post_data['sign'] = strtoupper($sign);
            $url = 'https://poll.kuaidi100.com/poll/query.do';    // 实时查询请求地址
            // 发送post请求
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
            $result = curl_exec($ch);
            // 第二个参数为true，表示格式化输出json
            $data = json_decode($result, true);
            $data['status'] = $data['result'];
           return $data;
        }

    }

    //撤单退回奖金
    public function returnBonus($order)
    {
        $order_id = $order['order_id'];
        $prize_arr = config('prize');
        $money_types = config('prizetype');
        $curtime = getCurTime();


        //1、分享奖、服务中心奖、复销奖、复销周管理奖、复销培育奖
        $map = [];
        $map[] = ['data_id','=',$order_id];
        $map[] = ['bonus_type','in', ['intro_bonus', 'team_bonus','chelv_bonus']];
        $share_bonus_arr = Db::name('bonus_detail')->where($map)->select();
        if ($share_bonus_arr) {
            foreach ($share_bonus_arr as $share_bonus) {
                Db::name('bonus_detail')->where('id', $share_bonus['id'])->setField('is_del', 1);
                Db::name('users')->where('user_id',$share_bonus['user_id'])->setDec('lj_bonus',$share_bonus['bonus']);
                if ($share_bonus['status'] == 1) {
                    $bonus_total = $share_bonus['bonus'];
                    $shouyi_bili = $share_bonus['shouyi_bili'];
                    $gouwuqaun_bili = $share_bonus['gouwuquan_bili'];
                    $gouwuqaun = bcmul($bonus_total, $gouwuqaun_bili / 100);
                    $shouyi = bcmul($bonus_total, $shouyi_bili / 100);
                    $desc = $order_id . '撤单，' . $prize_arr[$share_bonus['bonus_type']] . '撤回';
                    $money_type = $money_types[$share_bonus['bonus_type']] ?? '0';
                    //dump($list['user_id'].'=>'.$list['bonus_type'].'=>'.$bonus_total.'=>'.$score.'=>'.$shouyi);
                    if ($gouwuqaun > 0) {
                        //dump($list['bonus_type']);
                        //dump($prize_arr);
                        $res = qianbao($share_bonus['user_id'], -$gouwuqaun, 'gouwuquan', $prize_arr[$share_bonus['bonus_type']], $desc, 0, $money_type);
                        if (!$res['status']) {
                            return $res;
                        }
                    }
                    if ($shouyi > 0) {
                        $res = qianbao($share_bonus['user_id'], -$shouyi, 'shouyi', $prize_arr[$share_bonus['bonus_type']], $desc, 0, $money_type);
                        if (!$res['status']) {
                            return $res;
                        }
                    }
                }
            }
        }
        //月度管理网业绩
        //if($order['leixing_id']==1 || $order['leixing_id']==5) {
        $userinfo = Db::name('users')->where('user_id', $order['user_id'])->find();
        if (!$userinfo) {
            $userinfo = Db::name('users_del')->where('user_id', $order['user_id'])->find();
        }
        //扣除自身复销业绩
        if ($order['leixing_id'] == 1) {
            //给推荐网减业绩
            $tjstr = $userinfo['tjstr'];
            Db::name('users')->where(['user_id' => ['in', $tjstr]])->setDec('team_yeji', $order['total_shop_price']);
        }
        //会员级别降级
//        $all_pv_total = Db::name('order')
//            ->where(['leixing_id'=>['in',[1,5]],'order_status'=>['gt',0],'order_id'=>['neq',$order['order_id']],'user_id'=>$order['user_id']])
//            ->sum('total_pv');
//        //echo Db::getLastSql();
//        $user_level_pv = Db::name('user_level')->where('rank',$userinfo['level'])->value('up_pv');
//        //echo Db::getLastSql();
//        //订单pv不够，降级
//        //dump($all_pv_total.'=>'.$user_level_pv);
//        if($all_pv_total<$user_level_pv){
//            $new_level = Db::name('user_level')->where(['up_pv'=>['elt',$all_pv_total]])->order('rank desc')->find();
//            //插入升级记录
//            $insert = array();
//            $insert['username'] = $userinfo['username'];
//            $insert['old'] = $userinfo['level'];
//            $insert['new'] = $new_level['rank'];
//            $insert['up_money'] = 0;
//            $insert['w_time'] = $curtime;
//            $insert['desc'] = "删除订单".$order_id.'扣除pv'.$order['total_pv'];
//            $rs = Db::name('LevelLog')->add($insert);
//            Db::name('users')->where('user_id',$order['user_id'])->setField('level',$new_level['rank']);
//           // echo Db::getLastSql();
//
//        }
        //die('stop');
        //$this->downLevel1($order);
        return true;

    }

    public function order_to_ps($order_id,$ps_id=0){
        $order_info = Db::name('order')->where('order_id',$order_id)->find();
        if(!$ps_id){
            //未指定配送员，自动分配
            //获取最近的业务员
            $ps_users = Db::name('peisong_user')->where('status',1)->order('id desc')->select()->toArray();
            $to = '';
            foreach($ps_users as $k=>$ps_user){
                $to .= $ps_user['longitude'].','.$ps_user['latitude'].';';
            }
            $res = logic('MapQQ')->getDirectionDistanceMatrix($order_info['longitude'], $order_info['latitude'], $to);
            if($res['status']==0){
                return ['status'=>0,'msg'=>'获取配送员失败'.$res['message']];
            }
            $distance_arr = $res['distance_arr'];
            $distance = min($distance_arr);
            $min_keys = array_keys($distance_arr,$distance);
            $ps_user = $ps_users[$min_keys[0]]??'';
        }else{
            $ps_user = Db::name('peisong_user')->where('status',1)->where('id',$ps_id)->find();
        }
        if(!$ps_user){
            return ['status'=>0,'msg'=>'没有可用的配送员'];
        }
        $data = [
            'order_id' => $order_id,
            'ps_id' => $ps_id,
            'ps_user_id' => $ps_user['user_id'],
            'ticheng' => $order_info['shipping_price'],
            'w_time' => time(),
            'status' => 0,
        ];
        Db::name('ps_order')->insert($data);
        $data_o = [
            'ps_user_id' => $ps_user['user_id'],
            'order_status' => 2
        ];
        Db::name('order')->where('order_id',$order_id)->update($data_o);
        return ['status'=>1,'msg'=>'分配成功！'];
    }

    //获取订单商品列表
    public function get_order_goods($order_id){
        $order_goods = Db::name('order_goods')->where('order_id',$order_id)->select()->toArray();
        $refund_status_arr = $this->getRefundStatus();
        foreach($order_goods as $k=>$v){
            if($v['refund_goods_id']){
                $refund_good = Db::name('order_refund_goods')->where('id',$v['refund_goods_id'])->find();
                $refund_status_str = $refund_status_arr[$refund_good['status']]??'未知';
                $order_goods[$k]['refund_status'] = $refund_good['status'];
                $order_goods[$k]['refund_status_str'] = $refund_status_str;
            }else{
                $order_goods[$k]['refund_status'] = '';
                $order_goods[$k]['refund_status_str'] = '无';
            }
        }
        return $order_goods;
    }

    /**
     * 获取订单促销列表
     * @param $cartList
     * @param $cartPriceInfo
     * 1满额立减 2满额赠送 3加价换购 4满额打折 5满件打折 6满件立减
     */
    public function get_cuxiao($uid,$cartList,$cartPriceInfo){
        $user = Db::name('users')->where('user_id',$uid)->find();
        $proids = [];//商品id集合，用于计算促销
        $cids = [];//商品分类id集合，用于计算促销
        foreach($cartList as $suid =>$sval) {
            $goodsArr = $sval['goods'];
            $goods_ids = get_arr_column($goodsArr, 'goods_id');
            $proids = array_merge($proids, $goods_ids);
            //获取运费模板
            $goodsList = Db::name('Goods')->where('goods_id', 'IN', $goods_ids)->column('goods_id,template_id,is_free_shipping,cat_id', 'goods_id');
            $cids = array_merge($cids, array_column($goodsList, 'cat_id'));
        }
        $cuxiaolist = Db::name('cuxiao')
            ->where("(type in (1,2,3,4) and minprice<=".$cartPriceInfo['total_shop_price'].") or ((type=5 or type=6) and minnum<=".$cartPriceInfo['goods_num'].") ")
            ->where('starttime','<',time())->where('endtime','>',time())
            ->order('sort desc')->select()->toArray();
        $newcxlist = [];
        foreach($cuxiaolist as $k=>$v){
            $gettj = explode(',',$v['gettj']);
            if(!in_array('-1',$gettj) && !in_array($user['level'],$gettj)){ //不是所有人
                continue;
            }
            if($v['fwtype']==2){//指定商品可用
                $productids = explode(',',$v['productids']);
                if(!array_intersect($proids,$productids)){
                    continue;
                }
                if($v['type']==1 || $v['type']==2 || $v['type']==3 || $v['type']==4){//指定商品是否达到金额要求
                    $thistotalprice = 0;
                    foreach($cartList as $suid =>$sval) {
                        foreach ($sval['goods'] as $k2 => $product) {
                            if (in_array($product['id'], $productids)) {
                                $thistotalprice += $product['shop_price'] * $product['goods_num'];
                            }
                        }
                    }
                    if($thistotalprice < $v['minprice']){
                        continue;
                    }
                }
                if($v['type']==6 || $v['type']==5){//指定商品是否达到件数要求
                    $thistotalnum = 0;
                    foreach($cartList as $suid =>$sval) {
                        foreach ($sval['goods'] as $k2 => $product) {
                            if (in_array($product['goods_id'], $productids)) {
                                $thistotalnum += $product['goods_num'];
                            }
                        }
                    }
                    if($thistotalnum < $v['minnum']){
                        continue;
                    }
                }
            }
            if($v['fwtype']==1){//指定类目可用
                if(!$v['categoryids']) continue;
                $categoryids = explode(',',$v['categoryids']);
                $clist = Db::name('goods_category')->where('pid','in',$categoryids)->select()->toArray();
                foreach($clist as $kc=>$vc){
                    $categoryids[] = $vc['id'];
                    $cate2 = Db::name('goods_category')->where('pid',$vc['id'])->find();
                    $categoryids[] = $cate2['id'];
                }
                if(!array_intersect($cids,$categoryids)){
                    continue;
                }
                if($v['type']==1 || $v['type']==2 || $v['type']==3 || $v['type']==4){//指定商品是否达到金额要求
                    $thistotalprice = 0;
                    foreach($cartList as $suid =>$sval) {
                        foreach ($sval['goods'] as $k2 => $product) {
                            if (array_intersect(explode(',', $product['cid']), $categoryids)) {
                                $thistotalprice += $product['shop_price'] * $product['goods_num'];
                            }
                        }
                    }
                    if($thistotalprice < $v['minprice']){
                        continue;
                    }
                }
                if($v['type']==6 || $v['type']==5){//指定类目内商品是否达到件数要求
                    $thistotalnum = 0;
                    foreach($cartList as $suid =>$sval) {
                        foreach ($sval['goods'] as $k2 => $product) {
                            if (array_intersect(explode(',', $product['cid']), $categoryids)) {
                                $thistotalnum += $product['goods_num'];
                            }
                        }
                    }
                    if($thistotalnum < $v['minnum']){
                        continue;
                    }
                }
            }
            if($v['type']==4 || $v['type']==5){
                if($v['fwtype']==2) {
                    //商品
                    $cuxiaomoney = 0;
                    $prozkArr = array_combine(explode(',', $v['productids']), explode(',', $v['prozk']));
                    $pronumArr = array_combine(explode(',', $v['productids']), explode(',', $v['pronum']));
                    foreach($cartList as $suid =>$sval) {
                        foreach ($sval['goods'] as $k2 => $product) {
                            if ($prozkArr[$product['id']]) {
                                $prozk = $prozkArr[$product['id']];
                            } elseif (isset($prozkArr[$product['id']])) {
                                $prozk = $v['zhekou'];
                            } else {
                                $prozk = 10;
                            }
                            if ($v['type'] == 5 && $pronumArr[$product['id']] && intval($pronumArr[$product['id']]) > $product['goods_num']) {
                                $prozk = 10;
                            }
                            $cuxiaomoney += $product['shop_price'] * $product['goods_num'] * (1 - $prozk * 0.1);
                        }
                    }
                }elseif($v['fwtype']==1) {
                    //分类
                    $categoryPrice = 0;
                    foreach($cartList as $suid =>$sval) {
                        foreach ($sval['goods'] as $k2 => $product) {
                            $cids2 = explode(',', $product['cid']);
                            if (array_intersect($cids2, $categoryids)) {
                                $categoryPrice += $product['shop_price'] * $product['goods_num'];
                            }
                        }
                    }
                    $cuxiaomoney = $categoryPrice * (1 - $v['zhekou'] * 0.1);
                }else{
                    //全部
                    $cuxiaomoney = $cartPriceInfo['total_shop_price'] * (1 - $v['zhekou'] * 0.1);
                }
                $v['cuxiaomoney'] = round($cuxiaomoney,2);
            }
            $newcxlist[] = $v;
        }
        return $newcxlist;
    }
}